var app = getApp()
import * as Api from '../../utils/api.js'
Page({
  // 'https://api-merchant.nanxinwang.com/bapi/upload/20171228/file5a44e2a6db573c1b574c7fd0.jpg'
  data: {
    themeColors: '',

    files: [
    ],
    orderId: '',
    orderinfo: [],
    money: '',
    reason: '',
    isModeRefund: false,
    progress: 0,
    index: 0,
    paytotal:0
  },


  delFileItem(e){
    let self = this
    wx.showModal({
      title: '提示',
      content: '是否删除此张图片',
      success: function (res) {
        if (res.confirm) {
          console.log(self.data.files, self.data.files[e.currentTarget.dataset.itemindex])
          
        self.removeByValue(self.data.files, self.data.files[e.currentTarget.dataset.itemindex])
        self.setData({
          files: self.data.files
        })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },


  changeInputMoney(e) {
    console.log(e.detail.value.split(''))
    if (e.detail.value.split('')[1] && e.detail.value.split('')[1] == '.'){
      this.setData({
        money: e.detail.value.length > 4 ? e.detail.value.substring(0, 4) : e.detail.value
      })
    }else{
      this.setData({
        money: e.detail.value
      })
    }
    
  },
  changeInputReason(e) {
    this.setData({
      reason: e.detail.value
    })
  },
  getOrderInfo(orderid) {
    let self = this
    wx.request({
      method: 'post',
      url: app.globalData.baseUrl1 + '/order/queryorderdetail',
      data: {
        token: app.globalData.token,
        userId: app.globalData.userId,
        orderId: orderid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        console.log('订单详情', res.data)
        self.setData({
          orderinfo: res.data.data
        })
        if (res.data.data.refundOrder) {
          self.setData({
            money: res.data.data.refundOrder.refundAmount,
            reason: res.data.data.refundOrder.refundReason,
            isModeRefund: true
          })
        }
      }
    })
  },
  doRefund() {

    if (this.data.money> this.data.paytotal){
      wx.showModal({
        title: '',
        content: '退款金额不可以大于订单金额',
        showCancel: false,
        cancelText: '',
        cancelColor: '',
        confirmText: '知道了',
        confirmColor: '',
        success: function (res) {
        },
        fail: function (res) { },
        complete: function (res) { },
      })
      return
    }

    let url = app.globalData.baseUrl1 + '/order/refund/apply'
    if (this.data.isModeRefund) {
      url = app.globalData.baseUrl1 + '/order/refund/reapply'
    }
    let filesList = []
    this.data.files.forEach((item, index) => {
      filesList.push(item.filename)
    });
    let data = {
      token: app.globalData.token,
      userId: app.globalData.userId,
      money: this.data.money,
      orderId: this.data.orderId,
      refundImgs: filesList.join(','),
      reason: this.data.reason
    }
    let callBack = (res) => {
      console.log('申请退款', res)

      if (res == null) {
        console.log("网络请求错误1！");
        return;
      }

      if (res.data.status != 200) {
        wx.showModal({
          title: '',
          content: res.data.message,
          showCancel: false,
          cancelText: '',
          cancelColor: '',
          confirmText: '知道了',
          confirmColor: '',
          success: function (res) {
          },
          fail: function (res) { },
          complete: function (res) { },
        })
        return;
      }

      if (res.data.status == 200) {
        wx.showToast({
          title: '申请成功',
          icon: 'success',
          duration: 2000
        })
        wx.navigateBack({
          delta: 1,
        })
      }
    }
    Api.reqFormPost(url, data, callBack)

  },
  removeByValue(arr, val) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == val) {
        arr.splice(i, 1);
        break;
      }
    }
  },

  chooseImage: function (e) {

    if (this.data.files.length > 8) {
      
      return
    }


    var self = this;
    wx.chooseImage({
      count: 9 - this.data.files.length,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        let fileslen = self.data.files.length
        let uploadTask = []
        res.tempFilePaths.forEach((item, uploadIndex) => {
             self.data.files.push({ progress: 0, filename: item, index: fileslen + uploadIndex  })
          self.setData({
            files: self.data.files
          })
          console.log('添加时', self.data.files)
          let url = app.globalData.baseUrl1 + '/fileupload'
          uploadTask[uploadIndex] = wx.uploadFile({
            url: url,
            filePath: item,
            name: 'file',
            success: function (res1) {
              let opt = JSON.parse(res1.data)
              let files = self.data.files
              files[files[fileslen + uploadIndex].index] = { progress: 100, filename: opt.data.filename, index: files[files[fileslen + uploadIndex].index].index }
              self.setData({
                files: files,
              })
            },
            fail() {
            },
            complete() {
            }
          })
          uploadTask[uploadIndex].onProgressUpdate((res) => {
            let progress = 0

            if (res.progress > 1) {
              progress = res.progress - 1
            } else {
              progress = res.progress
            }
            self.data.files[self.data.files[fileslen + uploadIndex].index].progress = progress
            self.setData({
              files: self.data.files
            })
          })
        });
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片

      }
    })
  },
  onLoad: function (options) {


    wx.hideShareMenu()
    if (app.globalData.merchant === null) {
      app.doLogin(this.onLoad, this.onShow, options);
      return
    }
    
    this.setData({
      orderId: options.orderid,
      paytotal: options.paytotal,
      themeColors: app.globalData.merchant.themeColors
    })
    this.getOrderInfo(options.orderid)

  },
  previewImage: function (e) {
    let filesList = []
    this.data.files.forEach((item, index) => {
      filesList.push(item.filename)
    });
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: filesList // 需要预览的图片http链接列表
    })
  }
});